# Copyright (c) 2025 SenseTime. All Rights Reserved.
# Author: LazyLLM Team,  https://github.com/LazyAGI/LazyLLM

from flask import request
from flask_restful import reqparse

from core.restful import Resource
from libs.helper import build_response
from libs.login import login_required
from parts.urls import api

from .service import NotificationService


class NotificationListApi(Resource):
    """通知列表 API"""

    @login_required
    def get(self):
        """
        获取通知列表
        ---
        parameters:
          - name: page
            in: query
            type: integer
            default: 1
          - name: per_page
            in: query
            type: integer
            default: 20
          - name: unread_only
            in: query
            type: boolean
            default: false
        """
        parser = reqparse.RequestParser()
        parser.add_argument('page', type=int, default=1, location='args')
        parser.add_argument('per_page', type=int, default=20, location='args')
        parser.add_argument('unread_only', type=bool, default=False, location='args')
        args = parser.parse_args()

        try:
            result = NotificationService.get_user_notifications(
                page=args['page'],
                per_page=args['per_page'],
                unread_only=args['unread_only']
            )
            return build_response(result=result)
        except Exception as e:
            return build_response(message=str(e), status=500)

    @login_required
    def post(self):
        """
        创建通知（管理员功能）
        ---
        parameters:
          - name: body
            in: body
            required: true
            schema:
              type: object
              required:
                - title
                - content
              properties:
                title:
                  type: string
                content:
                  type: string
                type:
                  type: string
                  enum: [info, warning, error, success]
                link:
                  type: string
        """
        parser = reqparse.RequestParser()
        parser.add_argument('title', type=str, required=True, location='json')
        parser.add_argument('content', type=str, required=True, location='json')
        parser.add_argument('type', type=str, default='info', location='json')
        parser.add_argument('link', type=str, location='json')
        args = parser.parse_args()

        try:
            notification = NotificationService.create_notification(
                title=args['title'],
                content=args['content'],
                type=args['type'],
                link=args.get('link')
            )
            return build_response(result={'id': notification.id})
        except Exception as e:
            return build_response(message=str(e), status=500)


class NotificationDetailApi(Resource):
    """通知详情 API"""

    @login_required
    def patch(self, notification_id):
        """
        标记通知为已读
        ---
        parameters:
          - name: notification_id
            in: path
            type: integer
            required: true
        """
        try:
            notification = NotificationService.mark_as_read(notification_id)
            return build_response(result={'id': notification.id})
        except ValueError as e:
            return build_response(message=str(e), status=404)
        except Exception as e:
            return build_response(message=str(e), status=500)

    @login_required
    def delete(self, notification_id):
        """
        删除通知
        ---
        parameters:
          - name: notification_id
            in: path
            type: integer
            required: true
        """
        try:
            NotificationService.delete_notification(notification_id)
            return build_response(result={'success': True})
        except ValueError as e:
            return build_response(message=str(e), status=404)
        except Exception as e:
            return build_response(message=str(e), status=500)


class NotificationMarkAllReadApi(Resource):
    """标记所有通知为已读 API"""

    @login_required
    def post(self):
        """标记所有通知为已读"""
        try:
            NotificationService.mark_all_as_read()
            return build_response(result={'success': True})
        except Exception as e:
            return build_response(message=str(e), status=500)


# 注册路由
api.add_resource(NotificationListApi, '/notifications')
api.add_resource(NotificationDetailApi, '/notifications/<int:notification_id>')
api.add_resource(NotificationMarkAllReadApi, '/notifications/mark-all-read')
